import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../models/post_model.dart';
import '../../models/category_model.dart';
import '../../models/post_type.dart';
import '../../services/api_service.dart';
import '../../widgets/rich_text_editor.dart';
import '../../utils/logger.dart';
import 'package:base_flutter/src/network/network_exception.dart';

/// 编辑动态页面
class EditPostPage extends StatefulWidget {
  final PostModel post;

  const EditPostPage({super.key, required this.post});

  @override
  State<EditPostPage> createState() => _EditPostPageState();
}

class _EditPostPageState extends State<EditPostPage> {
  // 基础字段
  final _titleController = TextEditingController();
  String _selectedPostType = 'text';
  List<Category> _categories = [];
  Category? _selectedCategory;
  bool _isUpdating = false;

  // 动态类型配置
  final List<Map<String, dynamic>> _postTypes = [
    {'value': 'text', 'name': '图文', 'icon': Icons.text_fields, 'color': Colors.blue},
    {'value': 'article', 'name': '文章', 'icon': Icons.article, 'color': Colors.green},
    {'value': 'video', 'name': '视频', 'icon': Icons.videocam, 'color': Colors.purple},
    {'value': 'service', 'name': '商品', 'icon': Icons.shopping_bag, 'color': Colors.orange},
  ];

  // 图文类型字段
  String? _coverImageUrl;
  final _contentController = TextEditingController();
  List<String> _imageUrls = [];

  // 文章类型字段
  final _articleContentController = RichTextEditorController();

  // 视频类型字段
  String? _videoUrl;
  String? _videoCoverUrl;
  final _videoDescriptionController = TextEditingController();

  // 商品类型字段
  final _productNameController = TextEditingController();
  final _productPriceController = TextEditingController();
  final _productDescriptionController = TextEditingController();
  List<String> _productImages = [];

  @override
  void initState() {
    super.initState();
    _initializeData();
    _loadCategories();
  }

  /// 初始化数据
  void _initializeData() {
    _titleController.text = widget.post.content;
    _selectedPostType = _getPostTypeString(widget.post.postType);
    _coverImageUrl = widget.post.coverUrl;
    _imageUrls = List.from(widget.post.images);

    // 根据动态类型初始化相应字段
    switch (_selectedPostType) {
      case 'text':
        _contentController.text = widget.post.content;
        break;
      case 'article':
        _articleContentController.content = widget.post.content;
        break;
      case 'video':
        _videoUrl = widget.post.images.isNotEmpty ? widget.post.images.first : null;
        _videoDescriptionController.text = widget.post.content;
        break;
      case 'service':
        _productDescriptionController.text = widget.post.content;
        // 这里需要从后端获取商品详细信息
        break;
    }
  }

  /// 获取动态类型字符串
  String _getPostTypeString(PostType postType) {
    switch (postType) {
      case PostType.text:
        return 'text';
      case PostType.article:
        return 'article';
      case PostType.video:
      case PostType.videoCollection:
        return 'video';
      case PostType.service:
        return 'service';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('编辑动态'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 1,
        actions: [
          TextButton(
            onPressed: _isUpdating ? null : _updatePost,
            child: Text(
              '保存',
              style: TextStyle(
                color: _isUpdating ? Colors.grey : Colors.blue,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            _buildPostTypeSelector(),
            const SizedBox(height: 16),
            _buildTitleSection(),
            const SizedBox(height: 16),
            _buildCategorySection(),
            const SizedBox(height: 16),
            _buildContentSection(),
            const SizedBox(height: 100),
          ],
        ),
      ),
    );
  }

  /// 构建动态类型选择器
  Widget _buildPostTypeSelector() {
    return _buildCard(
      icon: Icons.category,
      title: '动态类型',
      child: Wrap(
        spacing: 12,
        runSpacing: 12,
        children: _postTypes.map((type) {
          final isSelected = _selectedPostType == type['value'];
          return GestureDetector(
            onTap: () => setState(() => _selectedPostType = type['value']),
            child: Container(
              width: (MediaQuery.of(context).size.width - 64) / 2,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: isSelected ? (type['color'] as Color).withOpacity(0.1) : Colors.grey[50],
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected ? type['color'] as Color : Colors.grey[300]!,
                  width: isSelected ? 2 : 1,
                ),
              ),
              child: Column(
                children: [
                  Icon(
                    type['icon'],
                    size: 32,
                    color: isSelected ? type['color'] as Color : Colors.grey[600],
                  ),
                  const SizedBox(height: 8),
                  Text(
                    type['name'],
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: isSelected ? type['color'] as Color : Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建标题输入
  Widget _buildTitleSection() {
    return _buildCard(
      icon: Icons.title,
      title: '标题',
      child: TextField(
        controller: _titleController,
        decoration: const InputDecoration(
          hintText: '请输入动态标题（2-50个字符）',
          border: OutlineInputBorder(),
        ),
        maxLength: 50,
      ),
    );
  }

  /// 构建分类选择
  Widget _buildCategorySection() {
    return _buildCard(
      icon: Icons.folder,
      title: '选择分类',
      child: DropdownButtonFormField<Category>(
        value: _selectedCategory,
        decoration: const InputDecoration(hintText: '请选择内容分类', border: OutlineInputBorder()),
        items: _categories.map((category) => DropdownMenuItem(value: category, child: Text(category.name))).toList(),
        onChanged: (category) => setState(() => _selectedCategory = category),
      ),
    );
  }

  /// 构建内容区域（根据类型动态显示）
  Widget _buildContentSection() {
    switch (_selectedPostType) {
      case 'text':
        return _buildTextContentSection();
      case 'article':
        return _buildArticleContentSection();
      case 'video':
        return _buildVideoContentSection();
      case 'service':
        return _buildServiceContentSection();
      default:
        return _buildTextContentSection();
    }
  }

  /// 图文内容区域
  Widget _buildTextContentSection() {
    return Column(
      children: [
        _buildCard(
          icon: Icons.image,
          title: '封面图片',
          child: GestureDetector(
            onTap: _selectCoverImage,
            child: Container(
              width: double.infinity,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: _coverImageUrl != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        children: [
                          Image.network(_coverImageUrl!, fit: BoxFit.cover, width: double.infinity, height: double.infinity),
                          Positioned(
                            top: 8, right: 8,
                            child: GestureDetector(
                              onTap: () => setState(() => _coverImageUrl = null),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: const BoxDecoration(color: Colors.black54, shape: BoxShape.circle),
                                child: const Icon(Icons.close, color: Colors.white, size: 16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.add_photo_alternate, size: 32, color: Colors.grey[400]),
                        const SizedBox(height: 8),
                        Text('点击选择封面图', style: TextStyle(color: Colors.grey[600])),
                      ],
                    ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.edit,
          title: '文字描述',
          child: TextField(
            controller: _contentController,
            decoration: const InputDecoration(
              hintText: '分享你的想法...',
              border: OutlineInputBorder(),
            ),
            maxLines: 5,
            maxLength: 500,
          ),
        ),
      ],
    );
  }

  /// 文章内容区域
  Widget _buildArticleContentSection() {
    return Column(
      children: [
        _buildCard(
          icon: Icons.image,
          title: '文章封面',
          child: GestureDetector(
            onTap: _selectCoverImage,
            child: Container(
              width: double.infinity,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: _coverImageUrl != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        children: [
                          Image.network(_coverImageUrl!, fit: BoxFit.cover, width: double.infinity, height: double.infinity),
                          Positioned(
                            top: 8, right: 8,
                            child: GestureDetector(
                              onTap: () => setState(() => _coverImageUrl = null),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: const BoxDecoration(color: Colors.black54, shape: BoxShape.circle),
                                child: const Icon(Icons.close, color: Colors.white, size: 16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.add_photo_alternate, size: 32, color: Colors.grey[400]),
                        const SizedBox(height: 8),
                        Text('点击选择文章封面', style: TextStyle(color: Colors.grey[600])),
                      ],
                    ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.edit,
          title: '文章内容',
          child: RichTextEditor(
            controller: _articleContentController,
            hintText: '编写你的文章，支持图文混排...',
            minHeight: 200,
          ),
        ),
      ],
    );
  }

  /// 视频内容区域
  Widget _buildVideoContentSection() {
    return Column(
      children: [
        _buildCard(
          icon: Icons.videocam,
          title: '视频文件',
          child: GestureDetector(
            onTap: _selectVideo,
            child: Container(
              width: double.infinity,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: _videoUrl != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        children: [
                          if (_videoCoverUrl != null)
                            Image.network(_videoCoverUrl!, fit: BoxFit.cover, width: double.infinity, height: double.infinity),
                          const Center(
                            child: Icon(Icons.play_circle_filled, size: 48, color: Colors.white),
                          ),
                          Positioned(
                            top: 8, right: 8,
                            child: GestureDetector(
                              onTap: () => setState(() {
                                _videoUrl = null;
                                _videoCoverUrl = null;
                              }),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: const BoxDecoration(color: Colors.black54, shape: BoxShape.circle),
                                child: const Icon(Icons.close, color: Colors.white, size: 16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.video_library, size: 32, color: Colors.grey[400]),
                        const SizedBox(height: 8),
                        Text('点击选择视频文件', style: TextStyle(color: Colors.grey[600])),
                      ],
                    ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.edit,
          title: '视频描述',
          child: TextField(
            controller: _videoDescriptionController,
            decoration: const InputDecoration(
              hintText: '描述你的视频内容...',
              border: OutlineInputBorder(),
            ),
            maxLines: 3,
            maxLength: 200,
          ),
        ),
      ],
    );
  }

  /// 商品内容区域
  Widget _buildServiceContentSection() {
    return Column(
      children: [
        _buildCard(
          icon: Icons.shopping_bag,
          title: '商品信息',
          child: Column(
            children: [
              TextField(
                controller: _productNameController,
                decoration: const InputDecoration(
                  labelText: '商品名称',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _productPriceController,
                decoration: const InputDecoration(
                  labelText: '价格（元）',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.image,
          title: '商品图片',
          child: GestureDetector(
            onTap: _selectProductImages,
            child: Container(
              width: double.infinity,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: _productImages.isNotEmpty
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(_productImages.first, fit: BoxFit.cover, width: double.infinity, height: double.infinity),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.add_photo_alternate, size: 32, color: Colors.grey[400]),
                        const SizedBox(height: 8),
                        Text('点击选择商品图片', style: TextStyle(color: Colors.grey[600])),
                      ],
                    ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildCard(
          icon: Icons.edit,
          title: '商品描述',
          child: TextField(
            controller: _productDescriptionController,
            decoration: const InputDecoration(
              hintText: '详细描述你的商品...',
              border: OutlineInputBorder(),
            ),
            maxLines: 4,
            maxLength: 300,
          ),
        ),
      ],
    );
  }

  /// 构建卡片容器
  Widget _buildCard({required IconData icon, required String title, required Widget child}) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [BoxShadow(color: Colors.grey.withOpacity(0.1), spreadRadius: 1, blurRadius: 3, offset: const Offset(0, 1))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, color: Colors.blue[600], size: 20),
              const SizedBox(width: 8),
              Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black87)),
            ],
          ),
          const SizedBox(height: 12),
          child,
        ],
      ),
    );
  }

  /// 选择封面图片
  void _selectCoverImage() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(child: _buildImageSourceOption(Icons.photo_library, '相册选择', () { Navigator.pop(context); _pickImageFromGallery(); })),
                const SizedBox(width: 16),
                Expanded(child: _buildImageSourceOption(Icons.camera_alt, '拍照', () { Navigator.pop(context); _takePhoto(); })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建图片选择选项
  Widget _buildImageSourceOption(IconData icon, String title, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(color: Colors.grey[50], borderRadius: BorderRadius.circular(12), border: Border.all(color: Colors.grey[200]!)),
        child: Column(children: [Icon(icon, size: 32, color: Colors.blue[600]), const SizedBox(height: 8), Text(title, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500))]),
      ),
    );
  }

  /// 从相册选择图片
  Future<void> _pickImageFromGallery() async {
    try {
      final picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) await _uploadCoverImage(File(image.path));
    } catch (e) {
      _showErrorSnackBar('选择图片失败: $e');
    }
  }

  /// 拍照
  Future<void> _takePhoto() async {
    try {
      final picker = ImagePicker();
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      if (photo != null) await _uploadCoverImage(File(photo.path));
    } catch (e) {
      _showErrorSnackBar('拍照失败: $e');
    }
  }

  /// 上传封面图片
  Future<void> _uploadCoverImage(File imageFile) async {
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AlertDialog(content: Row(children: [CircularProgressIndicator(), SizedBox(width: 20), Text('正在上传图片...')])));
      final result = await ApiService().uploadPostImage(imageFile);
      Navigator.pop(context);
      if (result['code'] == 200 || result['code'] == 0) {
        setState(() => _coverImageUrl = result['data']);
        _showSuccessSnackBar('图片上传成功');
      } else {
        _showErrorSnackBar(result['message'] ?? '图片上传失败');
      }
    } catch (e) {
      Navigator.pop(context);
      _showErrorSnackBar('图片上传失败: $e');
    }
  }

  /// 选择视频
  void _selectVideo() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择视频', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(child: _buildImageSourceOption(Icons.video_library, '相册选择', () { Navigator.pop(context); _pickVideoFromGallery(); })),
                const SizedBox(width: 16),
                Expanded(child: _buildImageSourceOption(Icons.videocam, '录制', () { Navigator.pop(context); _recordVideo(); })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 从相册选择视频
  Future<void> _pickVideoFromGallery() async {
    try {
      final picker = ImagePicker();
      final XFile? video = await picker.pickVideo(source: ImageSource.gallery);
      if (video != null) await _uploadVideo(File(video.path));
    } catch (e) {
      _showErrorSnackBar('选择视频失败: $e');
    }
  }

  /// 录制视频
  Future<void> _recordVideo() async {
    try {
      final picker = ImagePicker();
      final XFile? video = await picker.pickVideo(source: ImageSource.camera);
      if (video != null) await _uploadVideo(File(video.path));
    } catch (e) {
      _showErrorSnackBar('录制视频失败: $e');
    }
  }

  /// 上传视频
  Future<void> _uploadVideo(File videoFile) async {
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AlertDialog(content: Row(children: [CircularProgressIndicator(), SizedBox(width: 20), Text('正在上传视频...')])));
      final result = await ApiService().uploadVideo(videoFile);
      Navigator.pop(context);
      if (result['code'] == 200 || result['code'] == 0) {
        setState(() {
          _videoUrl = result['data'];
          _videoCoverUrl = result['coverUrl'] ?? result['data'];
        });
        _showSuccessSnackBar('视频上传成功');
      } else {
        _showErrorSnackBar(result['message'] ?? '视频上传失败');
      }
    } catch (e) {
      Navigator.pop(context);
      _showErrorSnackBar('视频上传失败: $e');
    }
  }

  /// 选择商品图片
  void _selectProductImages() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择商品图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(child: _buildImageSourceOption(Icons.photo_library, '相册选择', () { Navigator.pop(context); _pickProductImagesFromGallery(); })),
                const SizedBox(width: 16),
                Expanded(child: _buildImageSourceOption(Icons.camera_alt, '拍照', () { Navigator.pop(context); _takeProductPhoto(); })),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 从相册选择商品图片
  Future<void> _pickProductImagesFromGallery() async {
    try {
      final picker = ImagePicker();
      final List<XFile> images = await picker.pickMultiImage();
      if (images.isNotEmpty) await _uploadProductImages(images.map((e) => File(e.path)).toList());
    } catch (e) {
      _showErrorSnackBar('选择图片失败: $e');
    }
  }

  /// 拍摄商品照片
  Future<void> _takeProductPhoto() async {
    try {
      final picker = ImagePicker();
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      if (photo != null) await _uploadProductImages([File(photo.path)]);
    } catch (e) {
      _showErrorSnackBar('拍照失败: $e');
    }
  }

  /// 上传商品图片
  Future<void> _uploadProductImages(List<File> imageFiles) async {
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AlertDialog(content: Row(children: [CircularProgressIndicator(), SizedBox(width: 20), Text('正在上传图片...')])));
      
      List<String> uploadedUrls = [];
      for (File imageFile in imageFiles) {
        final result = await ApiService().uploadPostImage(imageFile);
        if (result['code'] == 200 || result['code'] == 0) {
          uploadedUrls.add(result['data']);
        }
      }
      
      Navigator.pop(context);
      if (uploadedUrls.isNotEmpty) {
        setState(() => _productImages = uploadedUrls);
        _showSuccessSnackBar('图片上传成功');
      } else {
        _showErrorSnackBar('图片上传失败');
      }
    } catch (e) {
      Navigator.pop(context);
      _showErrorSnackBar('图片上传失败: $e');
    }
  }

  /// 加载分类
  Future<void> _loadCategories() async {
    try {
      final categoriesData = await ApiService().getContentCategories();
      setState(() {
        _categories = categoriesData.map((categoryJson) => Category.fromJson(categoryJson)).toList();
        if (_categories.isNotEmpty && _selectedCategory == null) {
          _selectedCategory = _categories.first;
        }
      });
    } catch (e) {
      setState(() {
        _categories = [
          Category(id: '1', name: '科技'),
          Category(id: '2', name: '文娱'),
          Category(id: '3', name: '游戏'),
          Category(id: '4', name: '旅行'),
          Category(id: '5', name: '美食'),
          Category(id: '6', name: '运动'),
          Category(id: '7', name: '教育'),
          Category(id: '8', name: '其他'),
        ];
        if (_selectedCategory == null) {
          _selectedCategory = _categories.first;
        }
      });
    }
  }

  /// 更新动态
  Future<void> _updatePost() async {
    if (!_validateForm()) return;
    
    setState(() => _isUpdating = true);
    
    try {
      Map<String, dynamic> updateData = _buildUpdateData();
      await ApiService().updatePost(widget.post.id, updateData);
      _showSuccessSnackBar('更新成功！');
      Navigator.pop(context, true); // 返回true表示更新成功
    } catch (e) {
      _showErrorSnackBar('更新失败: ${e is NetworkException ? e.message : '网络错误'}');
    } finally {
      setState(() => _isUpdating = false);
    }
  }

  /// 构建更新数据
  Map<String, dynamic> _buildUpdateData() {
    Map<String, dynamic> data = {
      'postType': _selectedPostType,
      'title': _titleController.text.trim(),
      'categoryId': _selectedCategory?.id,
      'categoryName': _selectedCategory?.name,
    };

    switch (_selectedPostType) {
      case 'text':
        data.addAll({
          'content': _contentController.text.trim(),
          'coverUrl': _coverImageUrl,
          'images': _imageUrls,
        });
        break;
      case 'article':
        data.addAll({
          'content': _articleContentController.content,
          'coverUrl': _coverImageUrl,
        });
        break;
      case 'video':
        data.addAll({
          'content': _videoDescriptionController.text.trim(),
          'videoUrl': _videoUrl,
          'coverUrl': _videoCoverUrl,
        });
        break;
      case 'service':
        data.addAll({
          'content': _productDescriptionController.text.trim(),
          'productName': _productNameController.text.trim(),
          'productPrice': double.tryParse(_productPriceController.text.trim()) ?? 0.0,
          'productImages': _productImages,
        });
        break;
    }

    return data;
  }

  /// 验证表单
  bool _validateForm() {
    if (_titleController.text.trim().isEmpty) {
      _showErrorSnackBar('请输入标题');
      return false;
    }
    if (_titleController.text.trim().length < 2) {
      _showErrorSnackBar('标题至少需要2个字符');
      return false;
    }
    if (_selectedCategory == null) {
      _showErrorSnackBar('请选择分类');
      return false;
    }

    switch (_selectedPostType) {
      case 'text':
        if (_contentController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入文字描述');
          return false;
        }
        break;
      case 'article':
        if (_articleContentController.content.trim().isEmpty) {
          _showErrorSnackBar('请输入文章内容');
          return false;
        }
        break;
      case 'video':
        if (_videoUrl == null) {
          _showErrorSnackBar('请选择视频文件');
          return false;
        }
        if (_videoDescriptionController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入视频描述');
          return false;
        }
        break;
      case 'service':
        if (_productNameController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入商品名称');
          return false;
        }
        if (_productPriceController.text.trim().isEmpty) {
          _showErrorSnackBar('请输入商品价格');
          return false;
        }
        if (_productImages.isEmpty) {
          _showErrorSnackBar('请选择商品图片');
          return false;
        }
        break;
    }

    return true;
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _articleContentController.dispose();
    _videoDescriptionController.dispose();
    _productNameController.dispose();
    _productPriceController.dispose();
    _productDescriptionController.dispose();
    super.dispose();
  }
}
